const path = require('path')
const fs = require('fs')
const rootDir = process.cwd()

async function getStat(path) {
  return new Promise((resolve, reject) => {
    fs.access(path, fs.constants.F_OK, (err) => {
      if (err) {
        resolve(false);
      } else {
        resolve(true);
      }
    })
  })
}

async function dirExists(dir) {
  const is_ = await getStat(dir)
  // console.log(is_)
  if (is_) {
    return true
  } else {
    const pathArr = dir.split('\\');
    let _path = '';
    for (let i = 0; i < pathArr.length; i++) {
      if (pathArr[i]) {
        if (i !== 0) _path += "\\"
        _path += `${pathArr[i]}`;
        if (!fs.existsSync(_path)) {
          fs.mkdirSync(_path);
        }
      }
    }
    return true
  }
}

async function upload(file, uploadDir = 'default') {
  const dirPath = path.join(rootDir, `./public/${uploadDir}/`)
  const is_ = await dirExists(dirPath)
  if (is_) {
    const reader = fs.createReadStream(file.path);
    const fileName = `${+new Date()}_${file.name}`
    const filePath = dirPath + fileName;
    console.log(filePath);
    // 创建可写流
    const upStream = fs.createWriteStream(filePath);
    // 可读流通过管道写入可写流
    reader.pipe(upStream);
    return `${uploadDir}/${fileName}`
  } else {
    return ""
  }
}

module.exports = upload